package com.zjcode.cas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zjcode.cas.mapper.CerCasUsersyncinfoMapper;
import com.zjcode.cas.model.CerCasUsersyncinfo;
import com.zjcode.cas.model.PreUsers;
import com.zjcode.cas.service.CasSyncService;
import com.zjcode.cas.service.CerCasUsersyncinfoService;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * @ClassName:CerCasUsersyncinfoServiceImpl
 * @功能：
 * @author：wlei
 * @日期：2023/2/7-00:12
 **/
@Service
@Slf4j
public class CerCasUsersyncinfoServiceImpl implements CerCasUsersyncinfoService {

    @Autowired
    private CerCasUsersyncinfoMapper cerCasUsersyncinfoMapper;
    @Autowired
    private CasSyncService casSyncService;

    @Override
    public List<CerCasUsersyncinfo> selectAllByIdIn(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return cerCasUsersyncinfoMapper.selectAllByIdIn(ids);
    }

    @Override
    public int insertByBatch(List<CerCasUsersyncinfo> cerCasUsersyncinfoList) {
        if (CollectionUtils.isEmpty(cerCasUsersyncinfoList)) {
            return 0;
        }
        return cerCasUsersyncinfoMapper.insertList(cerCasUsersyncinfoList);
    }

    @Override
    public int syncUserFormCas() {
        log.info("从cas中同步用户数据到临时表中");

        JSONObject obj = casSyncService.queryAllUsers();

        if (!Objects.isNull(obj)) {
            JSONArray data = obj.getJSONArray("data");
            if (Objects.isNull(data)) {
                return 0;
            }
            // data存在,将data转换成PreUsers的List
            List<PreUsers> preUsers = JSONObject.parseArray(data.toJSONString(), PreUsers.class);
            // 将List<PreUsers>转换成List<CerCasUsersyncinfo>
            List<CerCasUsersyncinfo> casUsersyncinfos = preUsers
                .stream()
                    .filter(preUser -> preUser.getSysids().contains("cancertem"))
                .map(each -> {
                    CerCasUsersyncinfo record = getCerCasUsersyncinfo(each);
                    return record;
                })
                .collect(Collectors.toList());

            List<String> ids = casUsersyncinfos
                .stream()
                .map(each -> each.getId())
                .collect(Collectors.toList());

            // 通过ids来判断数据是否存在
            List<CerCasUsersyncinfo> exitUsers = selectAllByIdIn(ids);

            // 移除已经存在过的数据
            casUsersyncinfos.removeIf(cerCasUsersyncinfo -> {
                String id = cerCasUsersyncinfo.getId();
                long count = exitUsers
                    .stream()
                    .filter(each -> Objects.equals(id, each.getId()))
                    .count();
                return count > 0;
            });

            if (casUsersyncinfos.size() > 0) {
                // 执行数据的写入
                insertByBatch(casUsersyncinfos);
                log.info("数据写入成功,一共写入数据:{}条", casUsersyncinfos.size());
                return casUsersyncinfos.size();
            } else {
                // 不执行数据的写入
                log.info("所有数据都已经存在");
                return 0;
            }
        }

        return 0;
    }

    @NotNull
    private static CerCasUsersyncinfo getCerCasUsersyncinfo(PreUsers each) {
        CerCasUsersyncinfo record = new CerCasUsersyncinfo();
        record.setId(each.getId());
        record.setUsername(each.getUsername());
        record.setPassword("Wny@2023");
        record.setRole(each.getRole());
        record.setName(each.getName());
        record.setTelephone(each.getTelephone());
        record.setEmail(each.getEmail());
        record.setPhoto("");
        record.setOrgcode(each.getOrgcode());
        record.setZonecode(each.getZonecode());
        record.setAddtime(each.getAddtime());
        record.setState(each.getState());
        record.setModytime(each.getModytime());
        record.setMkey(each.getKey());
        record.setZb(each.getZb());
        record.setDatasource(each.getDataSource());
        record.setDepartment(each.getDepartment());
        record.setAdddepartment(each.getAddDepartment());
        record.setModydepartment(each.getModyDepartment());
        record.setAddorg(each.getAddOrg());
        record.setModyuser(each.getModyUser());
        record.setModyorg(each.getModyOrg());
        record.setAdduser(each.getAddUser());
        record.setPosition(each.getPosition());
        record.setTitle(each.getTitle());
        record.setLinkedid(each.getLinkedId());
        record.setLinedep(each.getLineDep());
        record.setHead("");
        record.setModysource(each.getModySource());
        record.setUseridcard(each.getUserIdCard());
        record.setEdrusertype(each.getEdrUserType());
        record.setKey2(each.getKey2());
        record.setErbiaoupdatetime(each.getErbiaoUpdatetime());
        record.setUpdatepwddate(each.getUpdatePwdDate());
        record.setClientid(each.getClientId());
        // 0:未初始化 1:已初始化
        record.setIsInitSysuser(0);
        return record;
    }
}
